package org.ws.task.repository;

import com.google.common.collect.Maps;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ws.task.item.TaskInstance;

import java.util.Map;
import java.util.Set;

/**
 * 任务实例仓库
 */
public class TaskRepository {

    private static final TaskRepository instance = new TaskRepository();
    private final Map<String,TaskInstance> taskInstanceMap;

    private TaskRepository(){
        this.taskInstanceMap = Maps.newConcurrentMap();
    }

    public static TaskRepository getInstance(){
        return instance;
    }

    /**
     * 是否存在Task
     * @param name
     * @return
     */
    public boolean exists(String name){
        return this.taskInstanceMap.containsKey(name);
    }

    /**
     * 添加任务
     * @param instance
     */
    public void addTaskInstance(TaskInstance instance){
        this.taskInstanceMap.putIfAbsent(instance.getTaskConfig().getName(),instance);
    }

    /**
     * 获取任务
     * @param name
     * @return
     */
    public TaskInstance getTaskInstance(String name){
        if(!exists(name)){
            return null;
        }
        return this.taskInstanceMap.get(name);
    }

    public Set<String> taskNames(){
        return this.taskInstanceMap.keySet();
    }

    public TaskInstance removeTaskInstance(String name){
        if(!exists(name)){
            return null;
        }
        TaskInstance taskInstance = getTaskInstance(name);
        this.taskInstanceMap.remove(name);
        return taskInstance;
    }
}
